package com.hindua.tab.scr;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.hindua.ailaaicuaai.ChapterActivity;
import com.hindua.ailaaicuaai.MainActivity;
import com.hindua.ailaaicuaai.R;

public class StorySrc extends Fragment{
	private ViewGroup viewGroup;
	private WebView webView;
	private ProgressBar progressBar;
	private AdView adView;
	private int position;
	private int chapter;
	private ChapterActivity instance;
	private Button btnNext;
	private Button btnPrev;
	
	public StorySrc(int pos, int c, ChapterActivity cActivity) {
		this.position = pos;
		this.chapter = c;
		this.instance = cActivity;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(viewGroup == null) {
			viewGroup = (ViewGroup) inflater.inflate(R.layout.web_view, container, false);
			webView = (WebView) viewGroup.findViewById(R.id.web_view);
			progressBar = (ProgressBar) viewGroup.findViewById(R.id.progress_bar);
			btnNext = (Button) viewGroup.findViewById(R.id.btn_next);
			btnPrev = (Button) viewGroup.findViewById(R.id.btn_prev);
			adView = (AdView) viewGroup.findViewById(R.id.adView);
			AdRequest adRequest = new AdRequest();
	        adView.loadAd(adRequest);
	        
	        webView.setWebChromeClient(new WebChromeClient());
	        btnNext.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					getInstance().nextChapter(position - 1);
				}
			});
	        
	        btnPrev.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					getInstance().prevChapter(position + 1);
				}
			});
	        
			webView.setVisibility(View.GONE);
			webView.setWebViewClient(new WebViewClient() {

				@Override
				public void onPageFinished(WebView view, String url) {
					super.onPageFinished(view, url);
					progressBar.setVisibility(View.GONE);
				}				
			});
			webView.setVisibility(View.VISIBLE);
			webView.loadUrl(String.format("file:///android_asset/data/%d.htm", this.position));
			//webView.postUrl(String.format("%s/apps/app.php", MainActivity.HOST), String.format("c=%d", chapter).getBytes());
		} else {
			((ViewGroup) viewGroup.getParent()).removeView(viewGroup);
		}
		return viewGroup;
	}

	public ChapterActivity getInstance() {
		return instance;
	}
}
